package com.dao.impl;

import com.bean.BookBean;
import com.dao.BooksDao;
import com.util.JdbcUtil;
import com.util.PageUtil;

import java.sql.SQLException;
import java.util.List;

public class BooksDaoImpl implements BooksDao {

    @Override
    public int insert(BookBean bookBean) throws SQLException {
        return 0;
    }


    @Override
    public List<BookBean> queryData(Object... values) throws IllegalAccessException, SQLException, InstantiationException {
         String sql  = "SELECT * from dd_books LIMIT 1,10;";
         return JdbcUtil.queryData(sql,BookBean.class);
    }


    @Override
    public int update(BookBean b) throws SQLException {
        String sql = "update dd_books set book_name=?,isbn=?,author=?," +
                "   publish=?,publish_date=?,pages=?,book_price=?,mini_price=?,pic_url=?,counts=?,book_url=?,type_name=?" +
                " where book_id=?";

        return  JdbcUtil.insertOrUpdateOrDelete(sql,new Object[]{
                b.getBook_name(),b.getIsbn(),b.getAuthor(),
                b.getPublish(),b.getPublish_date(),b.getPages(),b.getBook_price(),b.getMini_price(),b.getPic_url(),b.getCounts()
                ,b.getBook_url(),b.getType_name(),b.getBook_id()
        });
    }


    @Override
    public int deleteById(Object id) throws SQLException{
        String sql ="delete from dd_books where book_id =?";

        return JdbcUtil.insertOrUpdateOrDelete(sql,new Object[]{id});
    }

    @Override
    public PageUtil<BookBean> queryDataPage(int currentPgae, int pageSize, BookBean bookBean) throws IllegalAccessException, SQLException, InstantiationException {

        String sql="select * from dd_books";

        Object[] values = null;

        if (bookBean!=null&&bookBean.getBook_name()!=null&&bookBean.getType_name()!=null){
            if (!bookBean.getType_name().equals("")&& bookBean.getBook_name().equals("")){
                 sql+= " where type_name=?";
                 values=new Object[]{bookBean.getType_name()};
            }else if (!bookBean.getBook_name().equals("") && bookBean.getType_name().equals("")){
                sql+=" where book_name like concat(\"%\",?,\"%\")";
                 values=new Object[]{bookBean.getBook_name()};
            }else if (!bookBean.getType_name().equals("") && !bookBean.getBook_name().equals("")){
                sql+=" where type_name=? AND book_name like concat(\"%\",?,\"%\")";
                values=new Object[]{bookBean.getType_name(),bookBean.getBook_name()};
            }
        }

        if (values==null){
            return JdbcUtil.queryDataByPage(sql,BookBean.class,currentPgae,pageSize);
        }else {
            return JdbcUtil.queryDataByPage(sql,BookBean.class,currentPgae,pageSize,values);
        }

    }
}
